import { _decorator, Component, Node, director } from 'cc';
const { ccclass, property } = _decorator;

export enum GameEvent {
    CONFIG_LOADED = "config_loaded",
    GAME_RESET = "game_reset",
    SCORE_UPDATED = "score_updated"
}

export interface GameConfig {
    facePoints: number;
    backPoints: number;
    flipDuration: number;
    targetScore: number;
}

@ccclass('GameManager')
export class GameManager extends Component {
    @property({ type: Number, tooltip: "翻到正面(face)的分数", step: 1 })
    facePoints = 0;

    @property({ type: Number, tooltip: "翻到反面(back)的分数", step: 1 })
    backPoints = 1;

    @property({ type: Number, tooltip: "目标分数", step: 1 })
    targetScore = 10;

    @property({ type: Number, tooltip: "翻硬币持续时间(秒)" })
    flipDuration = 2;

    @property({ type: Node, tooltip: "所有硬币的父节点" })
    coinsParent!: Node;

    @property({ type: Node }) scoreNode!: Node;

    // 新增：初始分数（避免开局0分无法生成硬币）
    @property({ type: Number, tooltip: "玩家初始分数", step: 1, min: 0 })
    initialScore = 2;

    private currentScore = 0;

    onLoad() {
        this.scheduleOnce(() => {
            this.initGame();
        }, 0);
    }

    private initGame() {
        // 初始化分数为配置的初始分数（替换原0值）
        this.currentScore = this.initialScore;
        this.broadcastConfig();
        this.scoreNode.emit(GameEvent.SCORE_UPDATED, this.currentScore, this.targetScore);
    }

    public broadcastConfig() {
        const config = {
            facePoints: this.facePoints,
            backPoints: this.backPoints,
            flipDuration: this.flipDuration,
            targetScore: this.targetScore
        };
        console.log(`GameManager 广播初始配置：翻转时间=${config.flipDuration}秒`);
        this.node.emit(GameEvent.CONFIG_LOADED, config);
    }

    onPropertyChanged() {
        this.facePoints = Math.max(0, this.facePoints);
        this.backPoints = Math.max(0, this.backPoints);
        this.targetScore = Math.max(1, this.targetScore);
        this.flipDuration = Math.max(0, this.flipDuration);
        this.broadcastConfig();
    }

    start() {
        this.registerEvents();
    }

    private registerEvents() {
        this.coinsParent.on(Node.EventType.CHILD_ADDED, this.onCoinAdded, this);
        this.coinsParent.children.forEach(child => {
            this.bindCoinEvent(child);
        });
    }

    private onCoinAdded(coinNode: Node) {
        this.bindCoinEvent(coinNode);
    }

    private bindCoinEvent(coinNode: Node) {
        if (coinNode.getComponent("CoinManager")) {
            coinNode.on("flip_result", this.onFlipResult, this);
        }
    }

    private onFlipResult(isFace: boolean) {
        const addPoints = isFace ? this.facePoints : this.backPoints;
        this.currentScore += addPoints;
        this.scoreNode.emit(GameEvent.SCORE_UPDATED, this.currentScore, this.targetScore);
        if (this.currentScore >= this.targetScore) {
            this.resetGame();
        }
    }

    // 新增：扣分方法（供CoinSpawner调用）
    public deductScore(amount: number) {
        if (amount <= 0) return;
        // 确保扣分后分数不低于0
        this.currentScore = Math.max(0, this.currentScore - amount);
        // 同步更新分数显示
        this.scoreNode.emit(GameEvent.SCORE_UPDATED, this.currentScore, this.targetScore);
        console.log(`GameManager: 扣分成功，扣除${amount}分，当前剩余${this.currentScore}分`);
    }

    // 新增：加分方法（用于生成失败时返还分数，可选）
    public addScore(amount: number) {
        if (amount <= 0) return;
        this.currentScore += amount;
        this.scoreNode.emit(GameEvent.SCORE_UPDATED, this.currentScore, this.targetScore);
    }

    // 新增：获取当前分数的公共方法（供CoinSpawner同步分数）
    public getCurrentScore(): number {
        return this.currentScore;
    }

    private resetGame() {
        // 重置时恢复为初始分数
        this.currentScore = this.initialScore;
        this.node.emit(GameEvent.GAME_RESET);
        this.initGame();
    }

    onDestroy() {
        this.coinsParent.off(Node.EventType.CHILD_ADDED, this.onCoinAdded, this);
        this.coinsParent.children.forEach(child => {
            child.off("flip_result", this.onFlipResult, this);
        });
    }
}